import os
import sys
import subprocess
import time

# 设置工作目录为kitten_tts_api
base_dir = os.path.dirname(os.path.abspath(__file__))
api_dir = os.path.join(base_dir, 'kitten_tts_api')
print(f"当前目录: {base_dir}")
print(f"后端目录: {api_dir}")

# 检查并安装依赖
def install_dependencies():
    print("正在使用清华大学PyPI镜像源安装核心依赖...")
    requirements_path = os.path.join(api_dir, 'requirements_simplified.txt')
    
    try:
        # 尝试使用清华大学镜像源安装
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", 
            "-i", "https://pypi.tuna.tsinghua.edu.cn/simple/",
            "-r", requirements_path
        ])
        print("核心依赖安装成功！")
    except subprocess.CalledProcessError as e:
        print(f"使用清华大学镜像源安装失败: {e}")
        print("尝试不使用镜像源安装...")
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", 
                "-r", requirements_path
            ])
            print("核心依赖安装成功！")
        except subprocess.CalledProcessError as e2:
            print(f"依赖安装失败: {e2}")
            print("请手动安装依赖后再启动服务。")
            sys.exit(1)

# 启动FastAPI服务
def start_server():
    try:
        print("正在启动Kitten TTS API服务...")
        print("服务将在 http://0.0.0.0:8000 运行")
        print("Swagger文档可访问: http://0.0.0.0:8000/docs")
        print("按 Ctrl+C 停止服务")
        
        # 切换到api目录
        os.chdir(api_dir)
        
        # 使用uvicorn启动FastAPI服务
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "main:app", 
            "--host", "0.0.0.0", 
            "--port", "8000",
            "--reload"  # 开发模式下自动重载
        ])
    except KeyboardInterrupt:
        print("服务已停止")
    except Exception as e:
        print(f"服务启动失败: {e}")

if __name__ == "__main__":
    # 安装依赖
    install_dependencies()
    
    # 等待短暂时间确保依赖安装完成
    time.sleep(1)
    
    # 启动服务
    start_server()